import {globalConfig} from "@/config/globalConfig";


let {baseUrl} = globalConfig
const uploadUrl = baseUrl + '/api/common/upload'
const viewUrl = baseUrl + '/api/common/static'

/**
 * 获取文件服务访问路径
 * @param url 文件路径
 * @returns {*|string}
 */
function getFileAccessHttpUrl(url) {
    if (url === undefined || url === null) {
        return url
    }
    if (url.startsWith('http') || url.startsWith('https')) {
        return url
    }
    return viewUrl + "/" + url
}
/**
 * 从文件服务访问路径中提取原始文件路径
 * @param url 文件服务访问路径
 * @returns {string|null} 原始文件路径，如果无法转换，返回原始 URL
 */
function getOriginalFilePath(url) {
    if (url === undefined || url === null) {
        return url;
    }
    // 检查是否是以viewUrl开头
    if (url.startsWith(viewUrl)) {
        // 提取 viewUrl 后面的路径部分
        return url.substring(viewUrl.length + 1); // +1 是为了去掉 '/'
    }
    // 如果不是以 viewUrl 开头，返回原始 URL
    return url;
}

/**
 * 封装一下 uni.request()
 * @param url
 * @param param
 * @returns {Promise<unknown>}
 */
async function getAction(url, param) {
    //过滤掉一些空值条件
    let param2 = JSON.parse(JSON.stringify(param))
    for (let [k,v] of Object.entries(param2)) {
        if (v === null || v === undefined || v === ''){
            Reflect.deleteProperty(param2, k)
        }
    }
    try {
        const [err, res] = await uni.request({
            url: getUrl(url),
            data: param2,
            method: 'GET'
        })
        if (err !== null) {
            console.log(err)
            return Promise.reject("请求失败")
        }
        // 请求成功
        return Promise.resolve(res.data)
    } catch (e) {
        return Promise.reject("请求异常")
    }
}

// getAction 更简洁
async function getActionSimple(url, param={}) {
    try {
        let res = await getAction(url, param)
        let {success, result, message} = res
        if (success) {
            return Promise.resolve(result)
        }
        return Promise.reject(message)
    } catch (e) {
        return Promise.reject(e)
    }
}

async function postAction(url, data) {
    try {
        const [err, res] = await uni.request({
            url: getUrl(url),
            data,
            method: 'POST',
            dataType: 'json',
        })
        if (err !== null) {
            return Promise.reject("请求失败")
        }
        // 请求成功
        return Promise.resolve(res.data)
    } catch (e) {
        return Promise.reject("请求异常")
    }
}

/**
 * 更方便的postAction
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 */
async function postActionSimple(url, data={}) {
    try {
        let res = await postAction(url, data)
        let {result, message, success} = res
        if (success) {
            return Promise.resolve(result)
        }
        return Promise.reject(message)
    } catch (e) {
        return Promise.reject(e)
    }
}
async function putAction(url, data) {
    try {
        const [err, res] = await uni.request({
            url: getUrl(url),
            data,
            method: 'PUT',
            dataType: 'json',
        })
        if (err !== null) {
            return Promise.reject("请求失败")
        }
        // 请求成功
        return Promise.resolve(res.data)
    } catch (e) {
        return Promise.reject("请求异常")
    }
}

async function putActionSimple(url, data) {
    try {
        let res = await putAction(url, data)
        let {result, message, success} = res
        if (success) {
            return Promise.resolve(message)
        }
        return Promise.reject(message)
    } catch (e) {
        return Promise.reject(e)
    }
}

async function deleteAction(url, param) {
    //过滤掉一些空值条件
    let param2 = JSON.parse(JSON.stringify(param))
    for (let [k,v] of Object.entries(param2)) {
        if (v === null || v === undefined || v === ''){
            Reflect.deleteProperty(param2, k)
        }
    }
    try {
        const [err, res] = await uni.request({
            url: getUrl(url),
            data: param2,
            method: 'DELETE'
        })
        if (err !== null) {
            console.log(err)
            return Promise.reject("请求失败")
        }
        // 请求成功
        return Promise.resolve(res.data)
    } catch (e) {
        return Promise.reject("请求异常")
    }
}
async function deleteActionSimple(url, param={}) {
    try {
        let res = await deleteAction(url, param)
        let {result, message, success} = res
        if (success) {
            return Promise.resolve(message)
        }
        return Promise.reject(message)
    } catch (e) {
        return Promise.reject(e)
    }
}


/**
 * 文件上传
 *
 * @param path
 * @returns {Promise<*>}
 */
async function uploadAction(path) {
    let [err, res] = await uni.uploadFile({
        url: uploadUrl,
        filePath: path,
        name: 'file',
        formData: {
            biz: 'wechat'
        }
    })
    if (err) {
        return Promise.reject(err)
    }
    let {data} = res
    let data2 = JSON.parse(data)
    let {message} = data2
    return Promise.resolve(message)
}

/**
 * 根据传入url获取 要请求的地址
 * @param url 传入的url
 * @returns {*|string}
 */
function getUrl(url) {
    if (url.startsWith("http") || url.startsWith("https")) {
        return url
    }
    return url.startsWith('/') ? baseUrl + url : baseUrl + '/' + url
}

export {
    getAction,
    getActionSimple,
    postAction,
    postActionSimple,
    putAction,
    putActionSimple,
    deleteAction,
    deleteActionSimple,
    getFileAccessHttpUrl,
    getOriginalFilePath,
    uploadAction,
    uploadUrl,
    viewUrl
}
